﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Runtime.CompilerServices.RuntimeHelpers;

namespace WindowsFormsApp
{
    public partial class Form22 : Form
    {
        public Form22()
        {
            InitializeComponent();
        }

        string randomCode = string.Empty;

        private void Form22_Load(object sender, EventArgs e)
        {
            freshCode();
        }

        private string CreateRandomCode(int codeCount)
        {
            string randomCode = "";
            string allChar = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,G,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z";
            string[] allCharArray = allChar.Split(',');
            Random rand = new Random();
            for (int i = 0; i < codeCount; i++)
            {
                randomCode += allCharArray[rand.Next(allCharArray.Length)].ToString();
            }
            return randomCode;
        }

        private Bitmap CreateImage(string code, int fontSize, string font, Color foreColor, Color bgColor)
        {
            int imageWidth = (code.Length * fontSize) + 40;
            int imageHeight = fontSize * 2 + 10;
            Bitmap image = new Bitmap(imageWidth, imageHeight);
            Graphics g = Graphics.FromImage(image);
            g.Clear(bgColor);
            Font f = new Font(font, fontSize, FontStyle.Bold);
            g.DrawString(code, f, new SolidBrush(foreColor), 1, 1);
            Random rnd = new Random();
            for (int i = 0; i < 100; i++)
            {
                int x = rnd.Next(imageWidth);
                int y = rnd.Next(imageHeight);
                g.FillRectangle(new SolidBrush(Color.FromArgb(rnd.Next())), x, y, 2, 2);
            }
            for (int i = 0; i < 50; i++)
            {
                int x1 = rnd.Next(imageWidth);
                int x2 = rnd.Next(imageWidth);
                int y1 = rnd.Next(imageHeight);
                int y2 = rnd.Next(imageHeight);
                g.DrawLine(new Pen(Color.FromArgb(rnd.Next()), 2), x1, y1, x2, y2);
            }
            return image;
        }
        private void freshCode()
        {
            randomCode = CreateRandomCode(5);
            pictureBox1.Image = CreateImage(randomCode, 35, "宋体", Color.Blue, Color.White);

        }
        private void button1_Click_1(object sender, EventArgs e)
        {
            if (randomCode.ToUpper() != textBox1.Text.ToUpper())
            {
                MessageBox.Show("验证码错误，请重新输入！");
                textBox1.Text = "";
                freshCode();
            }
            else
            {
                MessageBox.Show("正确!");
            }
        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {

        }
    }
}
